package com.glodon.paas.account.web.resource.internal;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.glodon.paas.account.api.bean.AccountConstant;
import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.account.service.UserService;
import com.glodon.paas.account.service.util.AccountConfig;
import com.glodon.paas.account.web.resource.UserResource;
import com.glodon.paas.account.web.util.UserInfoMappingUtil;
import com.glodon.paas.consts.StringConst;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.exception.i18n.ErrorCode;
@Component
@Path("/internal/user")
public class UserInternalResource extends UserResource{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(UserInternalResource.class);
	
	@Autowired
	private UserService userService;
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@Path("/{paramValue:.+}")
	public Object getUser( @Context HttpServletRequest request, 
						        @Context HttpServletResponse response, 
						        @PathParam("paramValue") String paramValue, 
//						        @QueryParam("account") String account,
						        @QueryParam("id") String id,
						        @QueryParam("status") String status){
		
		List<User> users = new ArrayList<User>();
		if(StringUtils.isNotEmpty(paramValue)){
			String[] values = paramValue.split(StringConst.SEPARATOR_COMMA);
			Set<String> searchedV = new HashSet<String>();
			for(String value : values){
				if(!searchedV.contains(value)){
					User user;
					if(id != null){
						user = userService.getUserById(value);
					}
					else if(StringUtils.isNumeric(status)){
						user = userService.getUserByAccountName(value, null, Integer.valueOf(status));
					}
					else{
						user = userService.getUserByAccountName(value, null, Integer.valueOf(1));
					}
					users.add(user);
					searchedV.add(value);
				}
			}
		}
		
		return users;
	}
	
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@Path("/{paramValue:.+}")
	public Object createInactiveUser( @Context HttpServletRequest request, 
						        @Context HttpServletResponse response, 
						        @PathParam("paramValue") String paramValue, 
						        @QueryParam("email") String email,
						        @QueryParam("mobile") String mobile){
			if(StringUtils.isNotEmpty(paramValue)){
				return UserInfoMappingUtil.fillUserPropertyText(userService.registerAccount(paramValue, null, AccountConfig.DEFAULT_PASSWORD, AccountConstant.USER_STATUS_INACTIVE));
			}
			else{
				throw PaasServerExceptionFactory.validateException("email adress or mobile is incorrect", null);
			}
	}
	
	@Override
	public String getUserId(HttpServletRequest request) {
		String userId = (String)request.getParameter("userId");
		if(StringUtils.isEmpty(userId)){
			userId = (String)request.getAttribute("userId");
			if(StringUtils.isEmpty(userId)){
				String email = (String)request.getParameter("email");
				if(StringUtils.isNotEmpty(email)){
					User user = userService.getUserByAccountName(email, AccountConstant.ACCOUNT_NAME_EMAIL,AccountConstant.USER_STATUS_ACTIVE);
					if(user == null){
						throw PaasServerExceptionFactory.notFoundException("can not find User["+email+"]", null).setErrorCode(ErrorCode.USER_NOT_EXIST);
					}
					else{
						userId = user.getId();
						request.setAttribute("userId", userId);
					}
				}
				else{
					throw PaasServerExceptionFactory.notFoundException("can not find User", null).setErrorCode(ErrorCode.USER_NOT_EXIST);
				}
			}
		}
		return userId;
	}
 	
	@Override
	public Logger getLoger() {
		return LOGGER;
	}	 
}
